import subprocess
import os
import time
import win32gui
import threading
import win32process
from pk.WindowManager import WindowManager

class ExeLauncher:
    def __init__(self, log_func=None):
        self.exe_path = None  # 单个程序路径
        self.launch_count = 5  # 默认启动5次
        self.log_func = log_func  # 日志回调
        self.found_windows = set()  # 记录已找到的窗口句柄
        self.lock = threading.Lock()  # 线程锁

    def set_exe_path(self, exe_path):
        """设置要启动的程序路径"""
        if exe_path:
            self.exe_path = exe_path
            if self.log_func:
                self.log_func(f"已设置启动程序: {exe_path}")

    def set_launch_count(self, count):
        """设置启动次数"""
        self.launch_count = count
        if self.log_func:
            self.log_func(f"设置启动次数: {count}")

    def find_new_window_by_title_pattern(self, exe_path):
        """通过标题模式查找新的窗口（未找到过的）"""
        exe_name = os.path.basename(exe_path).split('.')[0].lower()
        
        # 可能的窗口标题模式
        title_patterns = [
            exe_name,
            "梦幻西游",
            "梦幻西游:时空",
            "MyLauncher",
            "时空",
            "西游"
        ]
        
        # 查找所有匹配的窗口
        def enum_windows_callback(hwnd, windows):
            if win32gui.IsWindowVisible(hwnd):
                title = win32gui.GetWindowText(hwnd)
                if title:
                    for pattern in title_patterns:
                        if pattern.lower() in title.lower():
                            # 只添加未找到过的窗口
                            if hwnd not in self.found_windows:
                                windows.append(hwnd)
                                return False  # 停止枚举
            return True
        
        windows = []
        win32gui.EnumWindows(enum_windows_callback, windows)
        
        # 使用线程锁保护窗口检测和添加
        with self.lock:
            if windows:
                found_hwnd = windows[0]
                # 再次检查是否已被其他线程添加
                if found_hwnd not in self.found_windows:
                    title = win32gui.GetWindowText(found_hwnd)
                    if self.log_func:
                        self.log_func(f"找到新窗口: {title} (句柄: {found_hwnd})")
                        self.log_func(f"当前已找到的窗口数量: {len(self.found_windows)}")
                    # 记录已找到的窗口
                    self.found_windows.add(found_hwnd)
                    return found_hwnd
                else:
                    if self.log_func:
                        self.log_func(f"窗口 {found_hwnd} 已被其他线程检测到")
                    return None
            else:
                return None

    def start_single_exe(self, exe_path, index, insert_func=None):
        """启动单个程序的线程函数"""
        try:
            # 启动程序
            proc = subprocess.Popen(exe_path)
            
            if self.log_func:
                self.log_func(f"已启动第 {index + 1} 个程序: {exe_path}")
            
            # 等待窗口出现
            hwnd = None
            for wait_count in range(100):  # 10秒等待时间
                time.sleep(0.1)
                
                # 尝试查找新窗口
                hwnd = self.find_new_window_by_title_pattern(exe_path)
                if hwnd:
                    title = win32gui.GetWindowText(hwnd)
                    if self.log_func:
                        self.log_func(f"第 {index + 1} 个程序找到新窗口: {title} (句柄: {hwnd})")
                    break
                
                # 每2秒输出一次调试信息
                if wait_count % 20 == 0 and wait_count > 0:
                    if self.log_func:
                        self.log_func(f"第 {index + 1} 个程序等待中... ({wait_count/10:.1f}秒)")
            
            if hwnd:
                info = WindowManager.get_window_info(hwnd)
                if info and insert_func:
                    insert_func(info)
                if self.log_func:
                    self.log_func(f"第 {index + 1} 个窗口已添加: {info[1]}")
            else:
                if self.log_func:
                    self.log_func(f"未找到第 {index + 1} 个新窗口: {exe_path} (等待了10秒)")
                    
        except Exception as e:
            if self.log_func:
                self.log_func(f"启动第 {index + 1} 个程序失败: {exe_path}, 错误: {e}")

    def start_all_exe(self, insert_func=None):
        """并发启动指定次数的程序"""
        if not self.exe_path:
            if self.log_func:
                self.log_func("请先设置要启动的程序路径")
            return
        
        # 清空已找到的窗口记录
        self.found_windows.clear()
        
        if self.log_func:
            self.log_func(f"开始启动 {self.launch_count} 个程序，请稍候...")
            self.log_func(f"已清空窗口记录，准备检测新窗口")
        
        # 并发启动所有程序
        threads = []
        for i in range(self.launch_count):
            thread = threading.Thread(
                target=self.start_single_exe, 
                args=(self.exe_path, i, insert_func)
            )
            thread.daemon = True
            threads.append(thread)
            thread.start()
        
        # 不等待线程完成，让它们在后台运行
        # for thread in threads:
        #     thread.join() 